package com.xiao.mall.message.domain.converter;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import javax.persistence.AttributeConverter;
import java.util.Map;

/**
 * @author mingyuezheng
 */
public class MapStringConverter implements AttributeConverter<Map<String, Object>, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Map<String, Object> stringStringMap) {
        try {
            return objectMapper.writeValueAsString(stringStringMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    @Override
    public Map<String, Object> convertToEntityAttribute(String str) {

        if (!StringUtils.hasLength(str)) {
            return null;
        }

        try {
            Map<String, Object> stringMap = objectMapper.readValue(str, new TypeReference<Map<String, Object>>() {
            });
            return stringMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
